package com.xiyu.service.repository.mailbox.account;

import com.xiyu.service.vo.mailbox.mailboxAccount.MailboxAccountPageQueryInput;
import com.xiyu.service.model.mailbox.account.MailboxAccount;
import com.xiyu.service.model.mailbox.account.MailboxAccountTable;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.Page;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

import static com.xiyu.service.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

public interface MailboxAccountRepository extends JRepository<MailboxAccount, Long> {
    MailboxAccountTable mailboxAccountTable = MailboxAccountTable.$;

    default List<Long> findIdByOwnerId(Long ownerId){
        return sql().createQuery(mailboxAccountTable)
                .where(mailboxAccountTable.ownerId().eq(ownerId))
                .select(mailboxAccountTable.id())
                .execute();
    }

    default Page<MailboxAccount> pageQuery(MailboxAccountPageQueryInput inputVO, List<Long> ownerIds){
        return sql().createQuery(mailboxAccountTable)
                .where(mailboxAccountTable.sendName().likeIf(inputVO.getSendName()))
                .where(mailboxAccountTable.showName().likeIf(inputVO.getShowName()))
                .where(mailboxAccountTable.mailboxAccount().likeIf(inputVO.getMailboxAccount()))
                .where(mailboxAccountTable.ownerId().in(ownerIds))
                .orderBy(mailboxAccountTable.id().desc())
                .select(mailboxAccountTable).fetchPage(inputVO.getPageNo() - 1, inputVO.getPageSize());
    }

    default List<MailboxAccount> getTopAccount(Long ownerId){
        return sql().createQuery(mailboxAccountTable)
                .where(mailboxAccountTable.ownerId().eq(ownerId))
                .orderBy(mailboxAccountTable.id().desc())
                .select(mailboxAccountTable)
                .limit(5)
                .execute();
    }

    default void updateLastReceiveTime(Long accountId, LocalDateTime lastReceiveTime){
        sql().createUpdate(mailboxAccountTable)
                .where(mailboxAccountTable.id().eq(accountId))
                .set(mailboxAccountTable.lastReceiveTime(), lastReceiveTime)
                .execute();
    }

    Optional<MailboxAccount> findFirstByMailboxAccount(String mailboxAccount);

    List<MailboxAccount> findByOwnerId(Long ownerId);

    List<MailboxAccount> findByMailboxProtocolType(Integer mailboxProtocolType);


}